<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Project extends Controller_Initial_Page {
       
    public function action_ajax_show()
    {   
        if($_POST)
        {          
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project'); 
            $project = $project_model->get_project($_POST['id']);

            if($project)
            {
                $referrer = $this->request->referrer();
                
                $desktop_url = Route::url('desktop', array(
                  'id' => $project->user_url
                ), true);

                if($desktop_url != $referrer)
                {
                    throw new HTTP_Exception_404;
                }
                
                $force_preview = false;
                if(isset($_POST['preview']))
                    $force_preview = $_POST['preview'];
                
                $containers = ORM::factory('project_container')->get_containers($project->id);
                
                if($user_model AND $user_model->id == $project->user_id AND !$force_preview)
                {
                    //this is my project and not force preview
                    
                    $all_containers_view = $this->generate_containers($containers, true);
                    $project_view = View::factory('project/add_edit');
                    $project_view->set('is_all_published', $this->is_all_published($containers));
                    $project_view->set('licences', ORM::factory('project_licence')->get_all());
                    $project_view->set('licence_id',$project->licence_id);        
                }
                else
                {
                     //this is not my project or force preview 
                     //add user to view stats
                     $project_view_model = ORM::factory('project_view'); 
                     $project_view_model->project_id = $project->id;
                     $project_view_model->visitor_ip = $_SERVER['REMOTE_ADDR'];
                     $project_view_model->user_id = $user_model ? $user_model->id : null;
                     $project_view_model->save();
                     
                     //prepare vars to view
                     $views_amount = $project_view_model->get_amount($project->id);
                     
                     $project->date_created = Date::formatted_time($project->date_created, 'd.m.Y');
                     $project->date_modify = (!$project->date_modify) ? $project->date_created : Date::formatted_time($project->date_modify, 'd.m.Y');
                    
                     $project_comment_model = ORM::factory('project_comment');
                     $all_comments_amount = $project_comment_model->get_amount($project->id);
                     $comments_amount = ($all_comments_amount > 100) ? 100 : $all_comments_amount;
                     
                     $appreciation_model = ORM::factory('project_appreciation');
                     $appreciations = $appreciation_model->get_appreciations($project->id);
                     $already_voted = ($user_model AND $appreciation_model->is_appreciated($project->id, $user_model->id));
                     
                    $all_containers_view = $this->generate_containers($containers);
                    
                    //asign vars to view
                    $project_view = View::factory('project/show');
                    $project_view->set('comments', $this->generate_comments($project_comment_model->get_comments($project->id,100)))
                                 ->set('comments_amount', $comments_amount )
                                 ->set('all_comments_amount', $all_comments_amount)
                                 ->set('views_amount', $views_amount)
                                 ->set('appreciations', $appreciations)
                                 ->set('appreciations_amount', count($appreciations))
                                 ->set('already_voted', $already_voted);
                    
                    //check comment permission
                    $privacy = Privacy::factory($user_model ? $user_model->id : false, 
                                                $project->user_id);
                    $comment_project_permission = $privacy->comment_project_permission();
                    
                    if($privacy->comment_project_permission())
                    {
                        $project_view->set('profile', $user_model->user_profile);
                    } 
                }    
                
                //prepare tags 
                $tags = '';   
                $tags_ = ORM::factory('project_tag')->get_tags($project->id);
                foreach($tags_ as $tag)
                {
                    $tags .= $tag->name.',';
                }
   
           
                             
                $project_view->set('containers', $all_containers_view)
                             ->set('project', $project)
                             ->set('tags', $tags);
                
                $content = array('content' =>  $project_view->render());
                $this->response->body(json_encode($content));                           
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        }   
    }
    
    public function action_ajax_get_all_comments()
    {
        $project_model = ORM::factory('desktop_project',(int) $_POST['id'])->find();
        if($project_model->loaded())
        {
            $content = $this->generate_comments($project_model->comments);
            $content = array('content' => $content);

            //echo View::factory('profiler/stats');die;
            $this->response->body(json_encode($content));
        }
        else
        {
            throw new HTTP_Exception_404;
        }
    }
    
    private function generate_comments($comments)
    {
        $all_comments_view = '';
       
        for($i = 0; $i < count($comments); $i++)
        {
           $comment_view =  View::factory('project/comment/template', array('comment' =>  $comments[$i]));
           
           if(isset($comments[$i+1])AND $comments[$i+1]->parent_id != null AND $comments[$i]->parent_id == null) 
           {
               //open node
               $comment_view->set('node_type', 'open');
           }
           elseif((isset($comments[$i+1])AND $comments[$i+1]->parent_id == null AND $comments[$i]->parent_id != null)
                   OR
                  (!isset($comments[$i+1]) AND $comments[$i]->parent_id != null))
           {
               $comment_view->set('node_type', 'close');
           }
               
           $all_comments_view .= $comment_view->render(); 
        }
        
        return $all_comments_view;
    }
    
    private function generate_containers($containers, $edit = false)
    {
        $all_containers_view = '';
        
        foreach($containers as $container)
        {
            $container_data = json_decode($container->data);
            
            if(!$edit AND !$container->published)
                continue;
            
            switch($container_data->type)
            {
                case 'TEXT':
                    $container_view = View::factory('/project/container/text');
                    $container_view->set('text', $container_data->data->text);
                    break;

                case 'EMBED':
                    
                    $embed_provider = Embedmedia::factory($container_data->data->url);
                    
                    $container_view = View::factory('/project/container/embed');
                    $container_view->set('embed_object',$embed_provider->get_embed_view($container_data->data));
                    break;                 

                case 'PHOTO':
                    $file_model = ORM::factory('file',$container_data->data->id);
                    $image =  Image::factory($file_model->real_path());
                    $container_view = View::factory('/project/container/photo');
                    $container_view->set('photo',$file_model);
                    $container_view->set('photo_zoom',($image->width > 640));
                    break;
            }
            $container_view->set('id',$container->id);
            $container_view->set('published',(bool) $container->published);
            $container_view->set('edit',$edit);
            $all_containers_view .= $container_view->render();
        }
        
        return $all_containers_view;
    }
    
    private function is_all_published($containers)
    {
        foreach($containers as $container)
        {
            if(! (bool)$container->published)
            {
                return false;
            }
        } 

        return true;
    }


    public function action_ajax_appreciate()
    {
        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project',$_POST['id']);
            
            if ($project_model->loaded())
            {
                $appreciate_model = $project_model->appreciations;
               
                if($appreciate_model->where('user_id', '=', $user_model->id)->find()->loaded())
                {
                     //if i already voted
                    throw new HTTP_Exception_404;
                }
                else
                {
                    $appreciate_model->user_id = $user_model->id;
                    $appreciate_model->project_id = $project_model->id;
                    $appreciate_model->save();
                    
                    //add notification info
                     $notification_data = array(':project_id'      => $project_model->id,
                                                ':project_title'   => $project_model->item->title);

                     $notification_model = ORM::factory('notification');
                     $notification_model->user_id = $user_model->id;
                     $notification_model->resource_owner_id = $project_model->item->desktop->user_id;
                     $notification_model->event_type = 'PROJECT_APPRECIATED';
                     $notification_model->event_params = serialize($notification_data);
                     $notification_model->save();
                                        
                    $output = array('success' => true,
                                    'message' => __('you appreciate it'));
                
                    $this->response->body(json_encode($output));
                }
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        }

    }
    
    public function action_ajax_add_comment()
    {
        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project', $_POST['id']);
            
            if ($project_model->loaded() AND $user_model)
            {
                $project_owner = $project_model->item->desktop->user;
                $privacy = Privacy::factory( $user_model->id, $project_owner->id);
                if ($privacy->comment_project_permission())
                {
                    $project_comment_model = $project_model->comments;

                    try 
                    {
                        $project_comment_model->user_id = $user_model->id;
                        $project_comment_model->content = $_POST['content'];
                        $project_comment_model->project_id = $project_model->id;
                        
                        if (isset($_POST['parent_id']))
                            $project_comment_model->parent_id = $_POST['parent_id']; 
                                
                        $project_comment_model->save();

                        $project_comment_model->date_created = date('Y-m-d H:i:s');
                        $project_comment_template_view = View::factory('project/comment/template');
                        $project_comment_template_view->set('comment',$project_comment_model->get_comment($project_comment_model->id));

                        //add notification info
                         $notification_data = array(':project_id'      => $project_model->id,
                                                    ':project_title'   => $project_model->item->title,
                                                    ':comment_content' => $project_comment_model->content,
                                                    ':date_created'    => $project_comment_model->date_created);

                         $notification_model = ORM::factory('notification');
                         $notification_model->user_id = $user_model->id;
                         $notification_model->resource_owner_id = $project_owner->id;
                         $notification_model->event_type = 'PROJECT_COMMENT_ADDED';
                         $notification_model->event_params = serialize($notification_data);
                         $notification_model->save();
                        
                         //send message  project otowner about new comment if he want to about 
                         //don't send message to me about my comment
                         
                         if($user_model->id != $project_owner->id AND $project_owner->user_privacy->new_comment_notification)
                         { 
                             
                              // prepare email message  
                              $email_title_message = Kohana::message('email', 'new_comment.title');
                              $email_title_message = __($email_title_message, array(
                                                        ':name' => $user_model->user_profile->name.' '.$user_model->user_profile->surname
                                     ));
                              $main_config = Kohana::config('main');  

                              $email_template_view = View::factory('email/template');
                              $email_content_view = View::factory('email/new_comment');
                              $email_content_view->set('project_title',$project_model->item->title);
                              $email_content_view->set('comment_content',$project_comment_model->content);
                              $email_content_view->set('user_name',$user_model->user_profile->name);
                              $email_template_view->set('title', $email_title_message);
                              $email_template_view->set('content', $email_content_view);
                             
                              $send_email = Email::factory($email_title_message)
                                            ->message($email_template_view, 'text/html')
                                            ->to($project_owner->email)
                                            ->from($main_config->contact_mail, $main_config->contact_name)
                                            ->send();
                         
                             if(!$send_email)
                             {
                                  Log::instance()->add(Log::ERROR, 'Information about new comment about project could not be sent to '.$project_owner->email);
                             }       
                         }
                        
                        $output = array('success' => true,
                                        'message' => __('Your comment has been added'),
                                        'content' => $project_comment_template_view->render());

                        $this->response->body(json_encode($output));
                    }
                    catch (ORM_Validation_Exception $e)
                    {
                        $output = array('success' => false, 
                                        'message' => 'Oh no!', 
                                        'errors'  => $e->errors('validation'));

                        $this->response->body(json_encode($output));
                    }    
                }
                else
                {
                    throw new HTTP_Exception_403;
                }
                                    
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        } 
    }    
    

    
    public function action_ajax_add_container()
    {   
        //merge post and get because of fileUploader.js lack of real post method functionality
        $_POST = $_POST ? $_POST : $_GET;

        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $edit_mode = $user_model->loaded();
              
            $project_model = ORM::factory('desktop_project',$_POST['id']);
            if($project_model->loaded())
            {  
                if($user_model->id == $project_model->item->desktop->user_id)
                {
                    $last = $project_model->containers->order_by('order')->find();
                    $container_data = array();
                    
                    switch($_POST['type'])
                    {
                        case 'TEXT':
                            
                            $container_data['type'] = 'TEXT';
                            $container_view = View::factory('/project/container/text');
                            $container_view->set('text', Security::xss_clean($_POST['data']['text']));
                            $_POST['data']['text'] = Security::xss_clean($_POST['data']['text']);
                            break;

                        case 'EMBED':
                            $container_data['type'] = 'EMBED';
                            
                            $session = Session::instance();
                            if($embed_data = $session->get('embed_data') AND isset($embed_data[$_POST['data']['url']]))
                            {
                                 if($embedmedia = Embedmedia::factory($_POST['data']['url']))
                                 {
                                     $container_view = View::factory('/project/container/embed');
                                     $container_view->set('embed_object', $embedmedia->get_embed_view($embed_data[$_POST['data']['url']]));
                                     $_POST['data'] = $embed_data[$_POST['data']['url']];            
                                 }
                                 else
                                 {
                                      throw new HTTP_Exception_404; 
                                 }     
                            }
                            else
                            {
                                 throw new HTTP_Exception_404; 
                            }
                            
                                                 
                            break;

                        case 'PHOTO':
                            
                            $file = Uploader::factory();
                            $errors = $file->validate('2M', array('jpg','jpeg','png'));
        
                            if(!$errors)
                            {
                               // save file info in db 
                               $file_model = ORM::factory('file');
                               $file_model->name      = $file->name;
                               $file_model->extension = $file->extension;
                               $file_model->size      = $file->size;
                               $file_model->folder    = 'project_photo/user_'.$user_model->id.
                                                        '/project_'.$project_model->id;       
                               $file_model->save();
                               
                               $_POST['data']['id'] = $file_model->id;
                               
                               //save photo on serwer
                               $target_directory = UPLPATH.'/project_photo/user_'.$user_model->id.
                                                           '/project_'.$project_model->id.'/';
                               $new_file_name = $file_model->id;
                               $ext = $file_model->extension;

                                // if directory doesn't exist - create 
                                if(!is_dir($target_directory))
                                    mkdir($target_directory, 0755, true);
            
                                $photo_zoom = true;
                                $image = Image::factory($file->tmp_name);
                                if($image->width > 840)
                                {
                                    $image->resize(840, NULL, Image::WIDTH);
                                }
                                $image->save($target_directory.$new_file_name.'.'.$ext);
                                
                                if($image->width > 640)
                                {
                                    $image->resize(640, NULL, Image::WIDTH);
                                }
                                else
                                {
                                    $photo_zoom = false;
                                }
                                $image->save($target_directory.$new_file_name.'_mini.'.$ext);           
                            }
                            else
                            {
                                echo json_encode($errors);
                                die;
                            }
                            
                            $container_data['type'] = 'PHOTO';
                            $container_view = View::factory('/project/container/photo');
                            $container_view->set('photo',$file_model);
                            $container_view->set('photo_zoom',$photo_zoom);
                            break;
                    }
                    
                    $container_data['data'] = $_POST['data'];
                    
                    $container_model = ORM::factory('project_container');
                    $container_model->project_id = $project_model->id;
                    $container_model->order = $last->order + 1;
                    $container_model->data = json_encode($container_data);
                    $container_id = $container_model->save();
                    $container_view->set('id', $container_id);   
                    $container_view->set('edit', $edit_mode);
                    $container_view->set('published', false);

                    $output = array('success' => true,
                                    'content' => $container_view->render());
                
                    $this->response->body(json_encode($output));
                }
                else
                {
                    throw new HTTP_Exception_404; //not my project
                }
            }
            else
            {
                throw new HTTP_Exception_404; //project not exists
            }
        }
        
    }
    
    public function action_add_container()
    {
        $this->auto_render = false;
        $this->action_ajax_add_container();
    }
    
    public function action_ajax_delete_container($id)
    {
       
        //$project_model = ORM::factory('desktop_project',$_POST['id']);
        $container_model = ORM::factory('project_container',(int) $id);
        
        if($container_model->loaded())
        {
            $user_model = Auth::instance()->get_user();
            $item_model = $container_model->project->item;
            
            if($user_model->id == $item_model->desktop->user_id)
            {
                $container = json_decode($container_model->data);
                
                if($container->type == 'PHOTO')
                {
                    $file_model = ORM::factory('file',$container->data->id);
                    
                    if($file_model->loaded())
                    {
                        //TODO: delete all releated files
                        unlink($file_model->real_path());
                        unlink($file_model->real_path('mini'));
                        
                        $file_model->delete();
                    }
                    
                }
                
                $container_model->delete();
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        }
        else
        {
            throw new HTTP_Exception_404;
        }
        
    }
    
    public function action_ajax_get_embed_info()
    {
        if($_POST)
        {
           if($embed_provider = Embedmedia::factory($_POST['page']))
           {
                $session = Session::instance();
               if($session->get('embed_data'))
               {
                   $session->set('embed_data',array());
               }
                
               $embed_data = $session->get('embed_data');
               $embed_data[$_POST['page']] = $embed_provider->get_info();
               $session->set('embed_data', $embed_data);
               
               if($embed_data)
               {
                    $output = array_merge(array('success' => true),
                                          $embed_provider->get_info_view($embed_data[$_POST['page']]));
                                   
               }
               else
               {
                    $output = array('success' => false);
               }   
           }
           else
           {
                $output = array('success' => false);
           }
           
           $this->response->body(json_encode($output));
        }    
    }
    
    public function action_internal_recent_project()
    {
        $user_model = Auth::instance()->get_user();
        $field_model = $user_model->fields;
        
        $fields = $field_model->select('id')->find_all()->as_array();
        foreach($fields as &$field)
        {
            $field = $field->as_array();
            $field = $field['id'];
        }    
        
        $project_model = ORM::factory('desktop_project');
        $projects = $project_model->get_projects(4,null,$fields);
        
        $project_recent_view = View::factory('project/recent');
        $project_recent_view->set('projects', $projects);
        $this->response->body($project_recent_view); 
    }
    
    public function action_ajax_get_tags()
    {
        if($_GET)
        {
            $tag_model = ORM::factory('project_tag');
            $tags = array();
            
            $orm_tags = $tag_model->select('name')->where('name', 'LIKE', $_GET['search'].'%')->group_by('name')->find_all();
            foreach($orm_tags as $tag)
            {
                $tags[] =  array(null, $tag->name, null,'<div style="padding: 10px">'.$tag->name.'</div>');
            }
            
            $this->response->body(json_encode($tags));
        }
    }
    
    public function action_ajax_update_tags()
    {
        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project',$_POST['id']);
            
            if($project_model->item->desktop->user_id == $user_model->id)
            {
                //this is my project 
               
                DB::delete('project_tags')->where('project_id', '=', $_POST['id'])->execute(); //delete all tags

                if($_POST['tags'] !== '')
                {
                    $tags = explode(',', $_POST['tags']);

                    foreach($tags as $tag)
                    {
                        $project_tag_model = ORM::factory('project_tag');
                        $project_tag_model->name = $tag;
                        $project_tag_model->project_id = $_POST['id'];
                        
                        try
                        {
                             $project_tag_model->save();
                        }
                        catch (ORM_Validation_Exception $e)
                        {
                             $output = array('success' => 'false', 
                                             'message' => 'Oh no!', 
                                             'errors'  => $e->errors('validation'));
                            
                             $this->response->body(json_encode($output));
                        }
                       
                    }
                }
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        }
    }
    
    public function action_ajax_update_licence()
    {
        if($_POST)
        {   
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project',$_POST['id']);
            
            if($project_model->item->user_id == $user_model->id)
            {
                //this is my project
                $project_model->licence_id = $_POST['licence'];
                $project_model->save();              
            }
            else
            {
                throw new HTTP_Exception_404;
            }
        }
        
    }
    
    public function action_ajax_publish_updates()
    {
        if($_POST)
        {
            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project');
            
            $project = $project_model->get_project($_POST['project_id']);
            if ($project->user_id == $user_model->id)
            {
                $project_container_model = ORM::factory('project_container');
                $updated_rows = $project_container_model->publish_all($_POST['project_id']);
                
                if($updated_rows != 0)
                {
                    //add notification
                    $notification_data = array(':project_id'      => $project->id,
                                               ':project_title'   => $project->title);
                    
                    if($project->date_modify == null)
                    {
                        $event_type = 'PROJECT_ADDED';
                        
                        //send email notification to all friends about it
                        
                        $email_title_message = Kohana::message('email', 'new_project.title');
                        $email_title_message = __($email_title_message, array(
                                            ':name' => $project->user_name.' '.$project->user_surname
                         ));
                        $main_config = Kohana::config('main');  

                        $email_template_view = View::factory('email/template');
                        $email_content_view = View::factory('email/new_project');
                        $email_content_view->set('project_title', $project->title);
                        $email_content_view->set('project_description', $project->description);
                        $email_template_view->set('title', $email_title_message);
                        $email_template_view->set('content', $email_content_view);
                        
                        $contact_model = ORM::factory('contact');
                        $contacts = $contact_model->get_contacts($project->user_id);
                        foreach($contacts as $contact)
                        {
                            if($contact->new_project_notification)
                            {
                                $send_email = Email::factory($email_title_message)
                                        ->message($email_template_view, 'text/html')
                                        ->to($contact->email)
                                        ->from($main_config->contact_mail, $main_config->contact_name)
                                        ->send();

                                if(!$send_email)
                                {
                                    Log::instance()->add(Log::ERROR, 'Information about new comment about project could not be sent to '.$contact->email);
                                }
                            }
                        }
                        
                    }
                    else
                    {
                        $event_type = 'PROJECT_UPDATED';
                    }
                    
                    $notification_model = ORM::factory('notification');
                    $notification_model->user_id = $user_model->id;
                    $notification_model->event_type = $event_type;
                    $notification_model->event_params = serialize($notification_data);
                    $notification_model->save();
                    
                    $item_model = ORM::factory('desktop_item',$project->item_id);
                    $item_model->date_modify = date('Y-m-d H:i:s' ,time());
                    $item_model->save();
                    
                    $output = array('success' => true);        
                    $this->response->body(json_encode($output));
                }
            }
            else
            {
                throw new HTTP_Exception_403;
            }
        }
    }
    
    public function action_ajax_get_embed_object()
    {
        if($_POST)
        {
            if (!$embedmedia = Embedmedia::factory($_POST['link'])) return;
            if (!$embed_info = $embedmedia->get_info()) return;

            $embed_view = $embedmedia->get_embed_view($embed_info);
            $modal_embed_view = View::factory('link/modal_embed');
            $modal_embed_view->set('embed_object',$embed_view);
            
            $content = array('content' => $modal_embed_view->render());
            $this->response->body(json_encode($content));
        }
    }

    public function action_ajax_create_thumbnail()
    {
        if($_POST)
        {
               $desktop_item_model = ORM::factory('desktop_item')->with('desktop')
                                                                 ->with('project')
                                                                 ->where('project.id', '=', $_POST['project_id'])
                                                                 ->find();

               $user_model = Auth::instance()->get_user();
               if($desktop_item_model->loaded() AND $desktop_item_model->desktop->user_id ==  $user_model->id)
               {
                   $file_model = $desktop_item_model->thumbnail;
                   if($file_model->loaded() and file_exists($file_model->real_path()))
                   {                      
                       unlink($file_model->real_path());
                   }
                               
                   $file_name = 'thumb_'.time();
                   $ext = strtolower(pathinfo($_POST['image_url'], PATHINFO_EXTENSION));
                   $target_directory = UPLPATH.'item_thumbnails/user_'.$user_model->id;  
                   $path_to_file = $target_directory.'/'.$file_name.'.'.$ext;       

                   $original_img_path = UPLPATH.'project_photo/user_'.$user_model->id.'/project_'.$_POST['project_id'].'/'.pathinfo($_POST['image_url'], PATHINFO_FILENAME).'_mini.'.$ext;  

                   $image = Image::factory($original_img_path);
                  
                   $image->crop((int) $_POST['w'], (int) $_POST['h'],(int) $_POST['x'], (int) $_POST['y']); 
                   
                   $image->resize(210,160,Image::INVERSE);

                    // if directory doesn't exist - create 
                    if(!is_dir($target_directory))
                        mkdir($target_directory, 0755, true);

                   $image->save($path_to_file);

                   $file_size = filesize($path_to_file);

                   // save file info in db 
                   $file_model->name      = $file_name;
                   $file_model->extension = $ext;
                   $file_model->size      = $file_size;
                   $file_model->folder    = 'item_thumbnails/user_'.$user_model->id;  
                   $file_model->save();

                   $desktop_item_model->thumbnail_id = $file_model->id;
                   $desktop_item_model->save();

                   $new_file_name = $file_model->id;
                   $new_path_to_file = $target_directory.'/'.$new_file_name.'.'.$ext;  

                   rename($path_to_file, $new_path_to_file);
                   
                   $output = array('success'   => true,
                                   'thumbnail_id'   => $file_model->id,
                                   'thumbnail_path' => $file_model->path(true, 'default', false));
                   
                   $this->response->body(json_encode($output));
               }    
        }
    }
    
    public function action_ajax_delete_thumbnail()
    {
        if($_POST)
        {

            $user_model = Auth::instance()->get_user();
            $project_model = ORM::factory('desktop_project')
                             ->with('desktop_item:desktop')
                             ->where('id', '=', $_POST['id'])
                             ->find();

            if($project_model->item->desktop->user_id ==  $user_model->id)
            {
                $file_model = ORM::factory('file', $project_model->item->thumbnail_id);

                if( $file_model->loaded())
                {
                    //delete file;                   
                    unlink($file_model->real_path());
                    $file_model->delete();

                    $output = array('success'   => true);
                    $this->response->body(json_encode($output));
                }
            } 
            else
            {
                throw new HTTP_Exception_403;
            }
        }
    }
    
       
}